package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 自媒体业务
 */
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper,WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;
    //图片前缀名
    @Value("${file.oss.prefix}")
    private String prefix;
    //图片阿里云地址前缀
    @Value("${file.oss.web-site}")
    private String webSite;
    /**
     * 图片上传到OSS
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //1,校验参数
        if(multipartFile==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2,判断当前用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR);
        }

        //3,处理上传的文件名，保证文件名的唯一性
        //保证文件名不重复,文件名前缀
        String fileNamePrefix = UUID.randomUUID().toString().replace("-", "");

        //获取原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //得到最后一个.的索引位置
        int index = originalFilename.lastIndexOf(".");
        //获取后缀名
        String fileNamePostfix = originalFilename.substring(index);
        //将文件名拼接一起
        String fileName = fileNamePrefix + fileNamePostfix;

        //4，执行文件上传到OSS
        String filePath="";
        try {
            filePath = fileStorageService.store(prefix, fileName, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR,"上传出现问题");
        }
        //5,将数据保存到数据表
        WmMaterial material = new WmMaterial();
        material.setUserId(user.getId());
        material.setUrl(filePath);
        material.setType((short)0);
        material.setIsCollection((short)1);
        material.setCreatedTime(new Date());
        save(material);

        //6，响应数据，在前端页面展示
        material.setUrl(webSite+material.getUrl());

        //5，操作成功
        return ResponseResult.okResult(material);
    }

    /**
     * 自媒体图片列表展示
     * @param dto
     * @return
     */
    @Override
    public ResponseResult imageList(WmMaterialDto dto) {
        //1,校验参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2,校验用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR,"用户不存在");
        }
        //2,传页码默认值
        dto.checkParam();

        //2,判读收藏是否有值，如果有查询收藏字段
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //pojo类型收藏值为1或0
        if(dto.getIsCollection()>0){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        //分页查询加上当前用户，并且按照倒排
        lambdaQueryWrapper.eq(WmMaterial::getUserId,user.getId());
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //构建分页器
        IPage<WmMaterial> page=new Page<>(dto.getPage(),dto.getSize());
        page(page,lambdaQueryWrapper);
        //获取总条数
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        //返回前端数据
        List<WmMaterial> wmMaterials = page.getRecords();
        //拼接图片路径
        wmMaterials.forEach(materials ->{
            materials.setUrl(webSite+materials.getUrl());
        });
        result.setData(wmMaterials);
        //响应
        return result;
    }


    /**
     * 图片删除
     * @param id
     * @return
     */
    @Autowired
    private WmNewMaterialMapper wmNewMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        //1,校验参数
        if(id==null ||id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2，判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR,"用户不存在");
        }

        //3，查询数据是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //4,判断用户信息是否被关联
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getId,id);
        Integer count = wmNewMaterialMapper.selectCount(lambdaQueryWrapper);
        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"数据关联，不能删除");
        }
        //5,删除数据
        removeById(id);

        //6,删除oss存储
        fileStorageService.delete(wmMaterial.getUrl());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏  收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id,Short isCollect) {
        //1,校验参数
        if(id==null ||id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2，判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR,"用户不存在");
        }

        //3，查询数据是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //4,执行更新
        update(Wrappers.<WmMaterial>lambdaUpdate().
                eq(WmMaterial::getId,id).
                eq(WmMaterial::getUserId,user.getId()).
                set(WmMaterial::getIsCollection,isCollect));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
